package cn.yav.web.request;

import cn.yav.date.Base64Util;
import cn.yav.entity.base.IsEmptyUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * All rights Reserved, Designed By www.yavyun.net
 *
 * @version V1.0
 * @Title: yavpingtai
 * @Package cn.yav.web.request
 * @Description: ${todo}
 * @author: zn
 * @date: 2019/12/12 15:28
 * @Copyright: 2019 www.yavyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙江智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */
public class HttpJWUtil {
    private static final Logger logger = LoggerFactory
            .getLogger(HttpJWUtil.class);
    public static String doPost(String urlStr,String param){
        HttpURLConnection connection = null;
        InputStream is = null;
        InputStreamReader rsd = null;
        BufferedReader br = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        StringBuffer sb = new StringBuffer();
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //不缓存
            connection.setUseCaches(false);
            //设置保活连接
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("charset", "UTF-8");
            connection.setRequestProperty("Content-type", "application/json");
            //接收的数据格式
            connection.setRequestProperty("accept", "application/json");
            //60秒连接超时
            connection.setConnectTimeout(60000);
            //60秒读取超时
            connection.setReadTimeout(60000);
            connection.connect();
            if(param != null && !"".equals(param)){
                os = connection.getOutputStream();
                osw = new OutputStreamWriter(os);
                bw = new BufferedWriter(osw);
                bw.write(param);
                bw.flush();
            }
            int status = connection.getResponseCode();
            if(status == 200){
                is = connection.getInputStream();
                rsd = new InputStreamReader(is,"UTF-8");
                br = new BufferedReader(rsd);
                String s;
                while((s = br.readLine()) != null){
                    sb.append(s);
                }
            }else{
                return "{\"ResuleState\":\"-1\",\"Msg\":\"连接异常\"}";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(br != null)br.close();
                if(rsd != null)rsd.close();
                if(is != null)is.close();
                if(bw != null)bw.close();
                if(osw != null)osw.close();
                if(os != null)os.close();
                if(connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info(sb.toString());
        return sb.toString();
    }
    /**
     * 通过图片的url获取图片的base64字符串
     * @param imgUrl    图片url
     * @return    返回图片base64的字符串
     */
    public static String image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len=is.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            return Base64Util.encode(outStream.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outStream != null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpUrl != null){
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }
    /***
     * 发送人脸信息到设备中
     * @param personId  添加或编辑人员的id
     * @param personName 添加或编辑人员的姓名
     * @param sex 添加或编辑人员的性别  1.女  2.男
     * @param personPhoto 添加或编辑人员的base64图片
     * @param action 添加还是编辑(editPerson 编辑  addPerson 添加 )
     * @param UUID  对应设备的UUID（唯一的）
     */
    public static void sendPersonalInformationToEuipment(String personId,String personName,String sex,String personPhoto,String action,String UUID,String url){
        String image2Base64="";
        if(!IsEmptyUtils.isEmpty(personPhoto)){
            image2Base64= image2Base64(personPhoto);
        }
        JSONObject json4 = new JSONObject();
        json4.put("PersonCode1", "");
        json4.put("PersonCode2", "");
        json4.put("PersonCode3", "");
        json4.put("PersonReserveName", "");
        json4.put("PersonParam1", 0);
        json4.put("PersonParam2", 0);
        json4.put("PersonParam3", 0);
        json4.put("PersonParam4", 0);
        json4.put("PersonParam5", 0);
        json4.put("PersonData1", "");
        json4.put("PersonData2", "");
        json4.put("PersonData3", "");
        json4.put("PersonData4", "");
        json4.put("PersonData5", "");
        JSONObject json3 = new JSONObject();
        json3.put("PersonId", personId);
        json3.put("PersonName", personName);
        json3.put("Sex", sex);
        json3.put("IDCard", "IDCard");
        json3.put("Nation", "Nation");
        json3.put("Birthday", "Birthday");
        json3.put("Phone", "Phone");
        json3.put("Address", "Address");
        json3.put("LimitTime",1);
        json3.put("EndTime","2019-01-01 00:00:00");
        json3.put("LimitTime","2020-01-01 00:00:00");
        json3.put("Label","Label");
        json3.put("PersonExtension",json4);
        json3.put("PersonPhoto",image2Base64);
        JSONObject json2 = new JSONObject();
        json2.put("Action", action);
        json2.put("PersonType", 2);
        json2.put("PersonInfo", json3);
        JSONObject json1 = new JSONObject();
        json1.put("Name", "personListRequest");
        json1.put("UUID", UUID);
        json1.put("TimeStamp", "1542594185");
        json1.put("Data", json2);
        String param =json1.toJSONString();
        doPost(url, param);
    }
    /***
     * 从设备中删除人员信息
     * @param personId 删除人的id
     * @param UUID  对应设备的UUID（唯一的）
     */
    public static void DeletePersonnelInformationToEuipment(String personId,String UUID, String url){
        JSONObject json2=new JSONObject();
        json2.put("Action", "deletePerson");
        json2.put("PersonType", 2);
        json2.put("PersonId", personId);
        JSONObject json1=new JSONObject();
        json1.put("Name", "personListRequest");
        json1.put("UUID", UUID);
        json1.put("TimeStamp", 1542594185);
        json1.put("Data", json2);
        String param =json1.toJSONString();
        doPost(url, param);
    }
}
